#coding:utf-8
from django.views.decorators.cache import cache_page,never_cache,cache_control
from django.db.models import Sum, Count
from django.http import HttpResponse,HttpResponseRedirect
from django.shortcuts import render_to_response
from django.contrib.auth.models import User
from django.contrib import auth
from django.db import transaction
from models import *
from forms import *  
from utils import *
from urllib import urlencode
from django.views.decorators.csrf import csrf_protect
from settings import UPLOAD_ROOT,MEDIA_ROOT   
try:
    import cStringIO as StringIO
except:
    import StringIO   
 
   
@never_cache
def index(request):
    header = 'all'
    tags = Tag.objects.all()
    apps = App.objects.order_by('-last_update')[0:30]
    topics = Topic.objects.hot_topics()                                                                                                                                
    return render_to_response('app.html', locals())

@never_cache
def app_os(request,head):
    header = head or 'all'
    tags = Tag.objects.all()
    try:
        if header == "all" :
            apps = App.objects.order_by('-last_update')[0:30]   
        else:
            apps = Tag.objects.get(name=header).app_tags.all()[0:30]
    except:
        apps = [] #
    topics = Topic.objects.hot_topics()                                                                                                                             
    return render_to_response('app.html', locals())

@never_cache
def add_app(request):
    if not request.user.is_staff:
        return Http404
    
    if request.method == "POST":      
        form = AppForm(request.POST,request.FILES) 
        if form.is_valid():
            try:    
                app = form.save(commit=False)
                cd = form.cleaned_data
                apptags = cd.get('fmtags','').split(',') or []
                pretags = cd.get('pretags',[])
                print pretags
                apptags.extend(pretags)
                apptags.append('app')   
                tags = []  
                for atag in apptags:
                    try:
                        tag = Tag.objects.get(name=atag)
                        tags.append(tag)
                    except:
                        tag = Tag.objects.create(name=atag)
                        tags.append(tag)                    
          
                app.user = request.user
                app.audit=True   
                app.save()
                for t in tags:
                    app.tags.add(t)                   
                
                form.save_m2m()


                title = u"新应用已经提交,请耐心等待审核通过"
                message = title
                backurl = "/app/"
                return render_to_response("redirect.html",locals())                
                
            except:
                import traceback
                traceback.print_exc()
                
                error = "提交机型失败"
                return render_to_response('error.html', locals())     
        else:
            return render_to_response('add_app.html', locals()) 
            
            
    elif request.method == 'GET':
        form = AppForm()    
        return render_to_response('add_app.html', locals())   

@never_cache
def detail(request,appid):
    app = App.objects.get(pk=appid)
    
    stat = AppStar.objects.filter(app=app).aggregate(Sum('value'), Count('value'),)
    if stat['value__count'] >0:
        import decimal
        stat_count = stat.get('value__count') or 0
        score_f = round(float(stat.get('value__sum')or 0)/stat_count or 0,1)
        score_val  = decimal.Decimal(str(score_f)) or 0

    
    tags = app.tags.all()
    comments = app.comments.extra(
        select={
            'user_image':'select image from  mobeir_userprofile where mobeir_comment.user_id = mobeir_userprofile.user_id',    
        }
    ).order_by("-last_update").select_related('user')
    
    features = AppFeature.objects.filter(app=app).order_by("-last_update").select_related('user')[0:10]
    
    app_photos = app.photos.all()
    app_photo_count= app.photos.count()

    return render_to_response('app_one.html', locals())       
  
@never_cache
def add_feature(request,appid):
    if not request.user.is_authenticated():
        return HttpResponseRedirect("/login/?%s"%urlencode({'next':'/app/feature/add/%s/'%appid}))     
    if request.method == "GET":
        try:
            app = App.objects.get(id=appid)
        except:
            error = "没有找到这个应用"
            return render_to_response('error.html', locals()) 
        return render_to_response('add_app_feature.html', locals())   
    elif request.method == "POST":
        appid = request.POST.get('appid')
        app = App.objects.get(id=appid)
        content = request.POST.get('content')
        ln = len(content)
        if ln ==0:
            messages.error(request,u"内容不能为空 ")
            return render_to_response('add_app_feature.html', locals(),context_instance=RequestContext(request))            
        
        if ln > 1024:
            messages.error(request,u"内容长度最多500个汉字 ")
            return render_to_response('add_app_feature.html', locals(),context_instance=RequestContext(request))             
            
        try:
            feature = AppFeature()
            feature.user = request.user
            feature.content = (content)
            feature.app = app
            feature.save()
            return HttpResponseRedirect("/app/detail/%s/"%appid)
        except:
            import traceback
            traceback.print_exc()
            error = "内容添加失败了，请稍后再试"
            return render_to_response('error.html', locals()) 
                                                                 
@never_cache
def add_comment(request,appid):
    if not request.user.is_authenticated():
        return HttpResponseRedirect("/login/?%s"%urlencode({'next':'/app/comment/add/%s/'%appid}))     
    if request.method == "GET":
        try:
            app = App.objects.get(id=appid)
        except:
            error = "没有找到这个应用"
            return render_to_response('error.html', locals()) 
        return render_to_response('add_app_comment.html', locals())   
    elif request.method == "POST":
        appid = request.POST.get('appid')
        app = App.objects.get(id=appid)
        star_val = request.POST.get('star_val') or 3
        content = request.POST.get('content')
        ln = len(content)
        if ln ==0:
            messages.error(request,u"内容不能为空 ")
            return render_to_response('add_app_comment.html', locals(),context_instance=RequestContext(request))            
        
        if ln > 1024:
            messages.error(request,u"内容长度最多500个汉字 ")
            return render_to_response('add_device_comment.html', locals(),context_instance=RequestContext(request))             
            
        try:
            comment = Comment()
            comment.user = request.user
            comment.star = int(star_val)
            comment.content = (content)
            comment.save()
            app.comments.add(comment)
            app.save()
            return HttpResponseRedirect("/app/detail/%s/"%appid)
        except:
            import traceback
            traceback.print_exc()
            error = "评论添加失败了，请稍后再试"
            return render_to_response('error.html', locals()) 
                                                                 
@never_cache
def star(request):
    if not request.user.is_authenticated():
        return HttpResponse(u"need login", mimetype="text/plain")
    if request.method =="POST":
        appid = request.POST.get('appid')
        star_value = request.POST.get('star')
        
                                                
        if not appid or not star_value:
            return HttpResponse("0", mimetype="text/plain")
        
        app = App.objects.get(id=appid)

        star = AppStar()
        star.user = request.user
        star.value = star_value
        star.app = app
        star.save()
   
        stat = AppStar.objects.filter(app=app).aggregate(Sum('value'), Count('value'),)
                         
        import decimal
        score_f = round(float(stat['value__sum'])/stat['value__count'],1)
        app.score  = decimal.Decimal(str(score_f))
        app.save()

        return HttpResponse(str(app.score), mimetype="text/plain")     






